<?php  // $Id: lib.php,v 1.7.2.5 2009/04/22 21:30:57 skodak Exp $

/**
 * Library of functions and constants for module ltcd
 * This file should have two well differenced parts:
 *   - All the core Moodle functions, neeeded to allow
 *     the module to work integrated in Moodle.
 *   - All the ltcd specific functions, needed
 *     to implement all the module logic. Please, note
 *     that, if the module become complex and this lib
 *     grows a lot, it's HIGHLY recommended to move all
 *     these module specific functions to a new php file,
 *     called "locallib.php" (see forum, quiz...). This will
 *     help to save some memory when Moodle is performing
 *     actions across all modules.
 */

/// (replace ltcd with the name of your module and delete this line)

$ltcd_EXAMPLE_CONSTANT = 42;     /// for example


/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will create a new instance and return the id number
 * of the new instance.
 *
 * @param object $ltcd An object from the form in mod_form.php
 * @return int The id of the newly inserted ltcd record
 */
function ltcd_add_instance($ltcd) {

    $ltcd->timecreated = time();

    # You may have to add extra stuff in here #

    return insert_record('ltcd', $ltcd);
}


/**
 * Given an object containing all the necessary data,
 * (defined by the form in mod_form.php) this function
 * will update an existing instance with new data.
 *
 * @param object $ltcd An object from the form in mod_form.php
 * @return boolean Success/Fail
 */
function ltcd_update_instance($ltcd) {

    $ltcd->timemodified = time();
    $ltcd->id = $ltcd->instance;

    # You may have to add extra stuff in here #

    return update_record('ltcd', $ltcd);
}


/**
 * Given an ID of an instance of this module,
 * this function will permanently delete the instance
 * and any data that depends on it.
 *
 * @param int $id Id of the module instance
 * @return boolean Success/Failure
 */
function ltcd_delete_instance($id) {

    if (! $ltcd = get_record('ltcd', 'id', $id)) {
        return false;
    }

    $result = true;

    # Delete any dependent records here #

    if (! delete_records('ltcd', 'id', $ltcd->id)) {
        $result = false;
    }

    return $result;
}


/**
 * Return a small object with summary information about what a
 * user has done with a given particular instance of this module
 * Used for user activity reports.
 * $return->time = the time they did it
 * $return->info = a short text description
 *
 * @return null
 * @todo Finish documenting this function
 */
function ltcd_user_outline($course, $user, $mod, $ltcd) {
    return $return;
}


/**
 * Print a detailed representation of what a user has done with
 * a given particular instance of this module, for user activity reports.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function ltcd_user_complete($course, $user, $mod, $ltcd) {
    return true;
}


/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in ltcd activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @return boolean
 * @todo Finish documenting this function
 */
function ltcd_print_recent_activity($course, $isteacher, $timestart) {
    return false;  //  True if anything was printed, otherwise false
}


/**
 * Function to be run periodically according to the moodle cron
 * This function searches for things that need to be done, such
 * as sending out mail, toggling flags etc ...
 *
 * @return boolean
 * @todo Finish documenting this function
 **/
function ltcd_cron () {
	
	echo "\n\n==========================================\n".
		 "   Starting sync with the LTCD servers".
		 "\n==========================================\n";
	
	if(is_callable('curl_init') && is_callable('curl_exec')){
		$conn = 'curl';
	}else{
		$conn = 'fget';
	}
	
	//Test connection with the LTCD server
	if( !web_comm('http://dev.ltcd.eu/index.php','curl',false) ){ 
		echo "Testing connection to the LTCD service.............FAILED!\n";
		echo "\n==========================================\n".
			  "              Sync FAILED!".
			  "\n==========================================\n\n";
		return false;
	}else{
		echo "Testing connection to the LTCD service.............OK!\n";
	}
	
	
	//================PUSH DATA TO THE LTCD SERVERS===================
	//Get data...
	//$res = get_records('user');
	//print_r($res);
	
	//===============PULL DATA FROM THE LTCD SERVERS==================
	
	echo "\n==========================================\n".
		 " Sync successful! All data is up to date!".
		 "\n==========================================\n\n";
    return true;
}

/*
 * Sync users between Moodle and LTCD.
 *   @direction: 
 *     - 0: from Moodle to LTCD only
 *     - 1: from LTCD to Moodle only
 *     - 2: Both 
 */
function sync_users($direction=0, $data) {
	$direction = 0; //Only Moodle->LTCD supported at the moment
	if($direction == 0 || $direction == 2){
		$m2l = sync_m2l($data);
	}
	if($direction == 1 || $direction == 2){
		$l2m = sync_l2m($data);
	}
	if(!$m2l || !$l2m) return false;
	return true;
}

/*
 * Send Moodle user data to the LTCD servers
 */
function sync_m2l($data) {
	echo "Sync: Moodle---->LTCD<br/>";
	$res = get_records('user');
	
	$params = "data=".$data;
	
	$resp = web_comm('http://dev.ltcd.eu/api_dev.php/call','curl',true,$params);
	echo $resp;
	
	return true;
}

/*
 * Send LTCD user data to Moodle
 */
function sync_l2m($data) {
	echo "LTCD---->Moodle<br/>";
	return true;
}

/*
 * Used for sending/receiving data to/from the LTCD servers
 */
function web_comm($url, $method="curl", $response=false, $paramstr="") {
	//Init
	$status = true;
	$resp = '';
	
	if($method == 'curl'){
		$c = curl_init();
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_URL, $url);
		if($paramstr != ""){
			curl_setopt ($c, CURLOPT_POST, 1);
	 		curl_setopt ($c, CURLOPT_POSTFIELDS, $paramstr);
	 		curl_setopt ($c, CURLOPT_FOLLOWLOCATION, 1);
		}
        $contents = curl_exec($c);
		$info = curl_getinfo($c);
        curl_close($c);
		
        if($contents){ 
			$resp =  $contents;
		}else{ 
			$status = false;
		}
	}else{
		//Set up context for the connection
		$ctx = stream_context_create(array(
		    'http' => array(
		        'timeout' => 1
		        )
		    )
		); 
		if(! $resp = file_get_contents($url, 0, $ctx)) $status = false;
		
	}
	
	return $response ? $resp : $status;
}

/**
 * Must return an array of user records (all data) who are participants
 * for a given instance of ltcd. Must include every user involved
 * in the instance, independient of his role (student, teacher, admin...)
 * See other modules as example.
 *
 * @param int $ltcdid ID of an instance of this module
 * @return mixed boolean/array of students
 */
function ltcd_get_participants($ltcdid) {
    return false;
}


/**
 * This function returns if a scale is being used by one ltcd
 * if it has support for grading and scales. Commented code should be
 * modified if necessary. See forum, glossary or journal modules
 * as reference.
 *
 * @param int $ltcdid ID of an instance of this module
 * @return mixed
 * @todo Finish documenting this function
 */
function ltcd_scale_used($ltcdid, $scaleid) {
    $return = false;

    //$rec = get_record("ltcd","id","$ltcdid","scale","-$scaleid");
    //
    //if (!empty($rec) && !empty($scaleid)) {
    //    $return = true;
    //}

    return $return;
}


/**
 * Checks if scale is being used by any instance of ltcd.
 * This function was added in 1.9
 *
 * This is used to find out if scale used anywhere
 * @param $scaleid int
 * @return boolean True if the scale is used by any ltcd
 */
function ltcd_scale_used_anywhere($scaleid) {
    if ($scaleid and record_exists('ltcd', 'grade', -$scaleid)) {
        return true;
    } else {
        return false;
    }
}


/**
 * Execute post-install custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function ltcd_install() {
    return true;
}


/**
 * Execute post-uninstall custom actions for the module
 * This function was added in 1.9
 *
 * @return boolean true if success, false on error
 */
function ltcd_uninstall() {
    return true;
}


//////////////////////////////////////////////////////////////////////////////////////
/// Any other ltcd functions go here.  Each of them must have a name that
/// starts with ltcd_
/// Remember (see note in first lines) that, if this section grows, it's HIGHLY
/// recommended to move all funcions below to a new "localib.php" file.


?>
